using UnityEditor;
using UnityEngine;
using System.IO;
using System.Text.RegularExpressions;

namespace FbxToPrefab
{
    public static class Handle
    {
        public static bool TryMakePrefabByFbx(GameObject fbxObj, string assetPath, out GameObject prefab)
        {
            prefab = null;
            // 使用正则表达式检查路径
            var match = Regex.Match(assetPath, @"Assets/ResourcesLib/Scene/(Scene\d+)/FBX/");
            if (!match.Success)
            {
                Debug.LogError("fbx所在目录不对");
                return false;
            }
            // 创建Prefab的保存路径
            string sceneName = match.Groups[1].Value; // 提取到的SceneXXX
            var prefabDir = $"Assets/Resources/Prefab/Scene/{sceneName}";
            var prefabPath = Path.Combine(prefabDir, Path.GetFileName(assetPath));
            prefabPath = Path.ChangeExtension(prefabPath, ".prefab");

            // 确保目录存在
            if (!Directory.Exists(prefabDir))
            {
                Directory.CreateDirectory(prefabDir);
                AssetDatabase.Refresh();
            }

            // 创建一个空物体作为根节点
            GameObject root = new GameObject(fbxObj.name);
            // 实例化fbxObj，并作为root的子节点
            GameObject fbxInstance = (GameObject)PrefabUtility.InstantiatePrefab(fbxObj);
            fbxInstance.transform.SetParent(root.transform, false);
            // 创建Prefab
            prefab = PrefabUtility.SaveAsPrefabAsset(root, prefabPath, out bool success);
            // 清理临时对象
            Object.DestroyImmediate(root);

            return success;
        }
    }
}